package com.hmall.search.controller;


import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemClient;
import com.hmall.item.pojo.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.config.MyRestHighLevelClient;
import com.hmall.search.pojo.ItemDoc;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/search")
public class SearchController {
    @Autowired
    @Qualifier("client")
    private RestHighLevelClient client;
    @Autowired
    private ItemClient itemClient;

    @GetMapping("addList")
    public void addList(@RequestParam Integer page, @RequestParam Integer size) throws IOException {
        // 1.创建Request
        BulkRequest request = new BulkRequest();
        //2.准备参数，添加多个新增的Request
        PageDTO<Item> pageDTO = itemClient.findList(page, size);
        List<Item> list = pageDTO.getList();
        for (Item item : list) {
            ItemDoc itemDoc = new ItemDoc(item);
            request.add(new IndexRequest("item").id(itemDoc.getId().toString())
                    .source(JSON.toJSONString(itemDoc), XContentType.JSON));
        }
        client.bulk(request, RequestOptions.DEFAULT);
    }

    @GetMapping("add")
    public void add(@RequestParam Integer page, @RequestParam Integer size) throws IOException {

        //2.准备参数，添加多个新增的Request
        PageDTO<Item> pageDTO = itemClient.findList(page, size);
        List<Item> list = pageDTO.getList();
        Item item = list.get(0);
        ItemDoc itemDoc = new ItemDoc(item);
        // 1.创建Request
        IndexRequest request = new IndexRequest("item").id(itemDoc.getId().toString());

        request.source(JSON.toJSONString(itemDoc), XContentType.JSON);

        client.index(request, RequestOptions.DEFAULT);
    }


}
